<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>添加商品</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <el-alert
        title="添加商品信息"
        type="info"
        center
        show-icon
        :closable="false"
      >
      </el-alert>
      <!-- 步骤 -->
      <el-steps
        :space="200"
        :active="activeIndex - 0"
        finish-status="success"
        align-center
      >
        <el-step title="基本信息"></el-step>
        <el-step title="商品参数"></el-step>
        <el-step title="商品属性"></el-step>
        <el-step title="商品图片"></el-step>
        <el-step title="商品内容"></el-step>
        <el-step title="完成"></el-step>
      </el-steps>
      <!-- tab栏区域 -->
      <el-form
        ref="addFormRef"
        label-width="100px"
        label-position="top"
        :model="addForm"
        :rules="addFormRulse"
      >
        <el-tabs
          :tab-position="'left'"
          v-model="activeIndex"
          :before-leave="beforeTabLeave"
          @tab-click="tabClick(activeIndex)"
        >
          <el-tab-pane label="基本信息" name="0">
            <el-form-item label="商品名称" prop="goods_name">
              <el-input v-model="addForm.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品价格" prop="goods_price">
              <el-input v-model="addForm.goods_price" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品重量" prop="goods_weight">
              <el-input v-model="addForm.goods_weight" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品数量" prop="goods_number">
              <el-input v-model="addForm.goods_number" type="number"></el-input>
            </el-form-item>
            <el-form-item label="商品分类" prop="goods_cat">
              <el-cascader
                v-model="addForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品参数" name="1">
            <el-form-item
              :label="item.attr_name"
              v-for="item in mangDataTable"
              :key="item.attr_id"
            >
              <el-checkbox-group v-model="item.attr_vals">
                <el-checkbox
                  v-for="(cb, index) in item.attr_vals"
                  :key="index"
                  :label="cb"
                  border
                  size="medium"
                ></el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品属性" name="2">
            <el-form-item
              v-for="item in onlyDataTable"
              :key="item.attr_id"
              :label="item.attr_name"
            >
              <el-input v-model="item.attr_vals"></el-input>
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane label="商品图片" name="3">
            <el-upload
              class="upload-demo"
              :action="uploadURL"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              list-type="picture"
              :headers="headerObj"
              :on-success="loadSuccess"
            >
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-tab-pane>
          <el-tab-pane label="商品内容" name="4">
            <!-- 富文本编辑组件 -->
            <quill-editor
              v-model="addForm.goods_introduce"
            />
            <!-- 添加商品按钮 -->
            <el-button type="primary" class="btnAdd" @click="add"
              >添加商品</el-button
            >
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-card>
    <!-- 图片预览 -->
    <el-dialog :visible.sync="previewVisible" title="图片预览" width="50%">
      <img :src="previewPath" class="previewImg" />
    </el-dialog>
  </div>
</template>

<script>
// import 'quill/dist/quill.core.css'
// import 'quill/dist/quill.snow.css'
// import 'quill/dist/quill.bubble.css'
// import { quillEditor } from 'vue-quill-editor'  
export default {
  name: "Add",
  components: {
    quillEditor,
  },
  data() {
    return {
      previewVisible: false,
      // 图片路径
      previewPath: "",
      // 上传照片的请求头
      headerObj: {
        Authorization: window.sessionStorage.getItem("token"),
      },
      // 上传照片的路径
      uploadURL: "http://127.0.0.1:8888/api/private/v1/upload",
      // 动态参数列表
      mangDataTable: [],
      // 静态参数列表
      onlyDataTable: [],
      // 获取到的商品分类列表
      cateList: [],
      // 级联选择框的配置对象
      cateProps: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      activeIndex: "0",
      addFormRulse: {
        goods_name: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price: [
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_weight: [
          { required: true, message: "请输入商品重量", trigger: "blur" },
        ],
        goods_number: [
          { required: true, message: "请输入商品数量", trigger: "blur" },
        ],
        goods_cat: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
      },
      addForm: {
        goods_name: "",
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        // 商品所属的分类数组
        goods_cat: [],
        pics: [],
        goods_introduce: " ",
        attrs: [],
      },
    };
  },
  methods: {
    // 获取商品分类
    async getCateList() {
      const { data: res } = await this.$http.get("/categories");
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类失败");
      this.cateList = res.data;
      // console.log(this.cateList);
    },
    // 级联选择器选择改变时
    handleChange() {
      // console.log(this.addForm.goods_cat);
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = [];
      }
    },
    // tab标签切换时的钩子函数，oldActiveName是即将离开的的标签页的name,如果return false就不会切换
    beforeTabLeave(activeName, oldActiveName) {
      if (oldActiveName == "0" && this.addForm.goods_cat.length !== 3) {
        this.$message.error("请先选择商品分类");
        return false;
      }
    },
    async tabClick(activeIndex) {
      if (activeIndex == "1") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "many",
            },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取动态参数列表失败");

        this.mangDataTable = res.data.map((item) => {
          item.attr_vals =
            item.attr_vals === "" ? [] : item.attr_vals.split(",");
          return item;
        });
        console.log(this.mangDataTable);
      } else if (activeIndex == "2") {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          {
            params: {
              sel: "only",
            },
          }
        );
        if (res.meta.status !== 200)
          return this.$message.error("获取动态参数列表失败");
        this.onlyDataTable = res.data;
        // console.log(res);
      }
    },
    // 点击图片预览效果
    handlePreview(file) {
      // 将图片的url保存
      this.previewPath = file.response.data.url;
      // 显示弹出框
      this.previewVisible = true;
    },
    // 点击移除图片操作
    handleRemove(file) {
      // 1.获取要删除的图片的路径
      const filePath = file.response.data.tmp_path;
      // 2.从pics中找到这个图片，并返回索引值
      const i = this.addForm.pics.findIndex((item) => {
        item.pic === filePath;
      });
      // 3.调用splice方法把图片从pics中移除
      this.addForm.pics.splice(i, 1);
      // console.log(this.addForm);
    },
    // 图片上传成功的事件
    loadSuccess(response) {
      // console.log(response);
      const picInfo = { pic: response.data.tmp_path };
      this.addForm.pics.push(picInfo);
    },
    add() {
      // console.log(this.addForm);
      this.$refs.addFormRef.validate(async (valid) => {
        // 如果验证失败之间return空
        if (!valid) {
          return this.$message.error("请填写必要的表单项");
        }
        // console.log(this.mangDataTable);
        // 处理动态参数
        this.mangDataTable.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_vals.join(","),
          };
          this.addForm.attrs.push(newInfo);
        });
        // 处理静态参数
        this.onlyDataTable.forEach((item) => {
          const newInfo = {
            attr_id: item.attr_id,
            attr_value: item.attr_value,
          };
          this.addForm.attrs.push(newInfo);
        });
        // 首先要拷贝一份addForm，然后用操作拷贝的这个数据，
        // 而不是原来的addForm，因为那可能会影响之前绑定这个数据的组件
        // 将goods_cat这个数组转换为用逗号拼接的字符串
        const obj = { ...this.addForm };
        obj.goods_cat = obj.goods_cat.join(",");
        // console.log(obj);
        // 如果验证成功就发起请求添加商品
        const { data: res } = await this.$http.post("/goods", obj);
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加商品失败");
        } else {
          this.$message.success("添加商品成功");
          this.$router.push("/goods");
        }
      });
    },
  },
  computed: {
    cateId() {
      if (this.addForm.goods_cat.length !== 3) {
        return null;
      } else {
        return this.addForm.goods_cat[2];
      }
    },
  },

  created() {
    this.getCateList();
  },
};
</script>

<style lang='less' scoped>
.el-checkbox {
  margin: 0 10px 0 0 !important;
}
.previewImg {
  width: 100%;
}
.btnAdd {
  margin-top: 15px;
}
</style>